package info.vanbeem.WikiMindDesktop;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.ToolBar;
import org.eclipse.swt.widgets.ToolItem;

import com.admc.util.IOUtil;

public class Utils {

	/*
	 * File utils.
	 */

	public static String readFile(final File file) throws IOException {
		return IOUtil.toString(file);
	}

	public static void writeFile(final File file, final String text) throws IOException {
		final FileOutputStream os = new FileOutputStream(file);
		final OutputStreamWriter writer = new OutputStreamWriter(os, "UTF8");
		writer.write(text);
		writer.close();
	}

	/*
	 * Popup menu and toolbar utils.
	 */
	
	public static final Menu buildPopupMenu(final Shell shell, final String items[], final Listener listener) {
		final Menu menu = new Menu (shell, SWT.POP_UP);
		for (int i = 0; i < items.length - 1; ) {
			final MenuItem item = new MenuItem (menu, SWT.PUSH);
			final String menutext = items[i++];
			final String menuaccelerator = items[i++];
			item.setText (menutext + "\tCtrl-" + menuaccelerator);
			item.setAccelerator(SWT.CTRL | menuaccelerator.charAt(0));
			item.setData(items[i++]);
			item.addListener(SWT.Selection, listener);
		}
		return menu;
	}
	
	public static void showPopupMenu(final ToolBar toolbar, final ToolItem toolitem, final Menu menu) {
		final Rectangle rect = toolitem.getBounds ();
		final Point pt = toolbar.toDisplay(new Point (rect.x, rect.y + rect.height));
		menu.setLocation(pt.x, pt.y);
		menu.setVisible(true);
	}

	public static ToolItem buildPopupToolItem(final ToolBar toolbar, final String text, final Menu enummenu) {
		final ToolItem enumitem = new ToolItem (toolbar, SWT.DROP_DOWN);
		enumitem.setText(text);
		enumitem.addListener (SWT.Selection, new Listener () {
			public void handleEvent (Event event) { Utils.showPopupMenu(toolbar, enumitem, enummenu); }
		});	
		return enumitem;
	}
	
	public static ToolItem buildPopupToolItem(final ToolBar toolbar, final String text, final String items[], final Listener listener) {
		final Menu enummenu = buildPopupMenu(toolbar.getShell(), items, listener);
		return buildPopupToolItem(toolbar, text, enummenu);
	}

}
